<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="query.goodsName"
          placeholder="商品名称"
          class="handle-input mr10"
          clearable
        ></el-input>
        <el-select
          clearable
          v-model="query.categoryId"
          placeholder="商品分类"
          class="handle-select mr10"
        >
          <el-option
            v-for="(item, index) in categoryList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <!-- <el-input
          v-model="query.partner"
          placeholder="合作商"
          class="handle-input mr10"
          clearable
        ></el-input> -->

        <el-select
          clearable
          v-model="query.companyId"
          placeholder="合作商"
          class="handle-select mr10"
        >
          <el-option
            v-for="(item, index) in partnerList"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
          <!-- <el-option key="2" label="湖南省" value="湖南省"></el-option> -->
        </el-select>

        <el-select
          clearable
          v-model="query.enableStatus"
          placeholder="商品状态"
          class="handle-select mr10"
        >
          <el-option key="1" label="上架" value="0"></el-option>
          <el-option key="2" label="下架" value="1"></el-option>
        </el-select>

        <!-- <div class="block" style="float: left; margin-right: 10px;">
          <el-date-picker
            v-model="value2"
            type="daterange"
            align="left"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </div> -->

        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button
          type="primary"
          @click="handleIncrease"
          v-if="pmPermissions.includes('product:commodity:save')"
          >新增</el-button
        >
        <el-button
          type="primary"
          @click="handleExport"
          v-if="pmPermissions.includes('product:commodity:export')"
          >导出</el-button
        >
        <el-button
          type="danger"
          class="handle-del"
          @click="delAllSelection"
          v-if="pmPermissions.includes('product:commodity:delete')"
          >删除</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="图片" align="center">
          <template slot-scope="scope">
            <el-image
              class="table-td-thumb"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          align="center"
          class="mr10"
          label="商品名称"
        ></el-table-column>
        <el-table-column
          prop="shortName"
          align="center"
          label="商品简称"
        ></el-table-column>

        <el-table-column label="兑换所需积分" align="center">
          <template slot-scope="scope">{{ scope.row.integral }}</template>
        </el-table-column>
        <el-table-column label="商品价格" align="center">
          <template slot-scope="scope">{{ scope.row.price }}</template>
        </el-table-column>

        <el-table-column
          prop="categoryName"
          align="center"
          label="商品所属分类"
        ></el-table-column>
        <el-table-column
          prop="companyName"
          align="center"
          label="合作商"
        ></el-table-column>
        <el-table-column
          prop="brief"
          align="center"
          label="商品简介"
        ></el-table-column>
        <el-table-column
          prop="memo"
          align="center"
          label="备注"
        ></el-table-column>

        <el-table-column label="是否热销" width="180" align="center">
          <template slot-scope="scope">
            <el-radio-group
              v-model="scope.row.radio"
              @change="selectHotSale(scope.row)"
            >
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="pmPermissions.includes('product:commodity:delete')"
              >删除</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="pmPermissions.includes('product:commodity:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              v-if="fromBannerIncrease"
              @click="getProductId(scope.$index, scope.row)"
              >获取商品ID</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import NProgress from "nprogress";
import util from "utils/util";
import { mapGetters } from "vuex";
export default {
  name: "productmanage",
  data() {
    var validatePrice = function(rule, value, callback) {
      if (value && parseInt(value) < 0) {
        return callback(new Error("价格不能为负值"));
      } else if (value.trim() == "") {
        return callback(new Error("必填不能为空"));
      }
      callback();
    };
    return {
      pmPermissions: [],
      query: {
        goodsName: "",
        categoryId: "",
        companyId: "",
        startTime: "",
        endTime: "",
        pageIndex: 1,
        pageSize: 20,
        enableStatus: "",
      },
      tableData: [],
      pageTotal: 0,
      ids: [],
      multipleSelection: [],
      // value2: "",
      fromBannerIncrease: false,
      // radio: "1"
      categoryList: [],
      partnerList: [],
    };
  },
  created() {
    console.log(this.$route.query.fromBannerIncrease);
    this.getData();
    this.pmPermissions = this.permissions;
    if (this.$route.query.fromBannerIncrease) {
      this.fromBannerIncrease = this.$route.query.fromBannerIncrease;
    } else {
      this.fromBannerIncrease = false;
    }

    // 获取商品分类
    this.getCategory();
    // 获取合作商
    this.getPartner();
  },

  watch: {
    "$route.path": function(newVal, oldVal) {
      console.log(newVal, oldVal);
      if (newVal == "/product-manage") {
        this.pmPermissions = this.permissions;
      }
      if (oldVal == "/product-increase") {
        if (this.$route.query.fromBannerIncrease) {
          this.fromBannerIncrease = this.$route.query.fromBannerIncrease;
        }
        this.getData();
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      // console.log(newVal, oldVal);
      this.pmPermissions = newVal;
    },
  },
  mounted() {},
  computed: {
    ...mapGetters(["permissions"]),
  },
  methods: {
    getCategory() {
      this.$axios
        .get("/product/commoditycategory/list", {
          params: {},
        })
        .then(({ data: res }) => {
          console.log(res);
          if (res.code !== 0) {
            return;
          }
          this.categoryList = res.data;
        });
    },
    getPartner() {
      this.$axios
        .get("/product/company/list", {
          params: {},
        })
        .then(({ data: res }) => {
          console.log(res);
          if (res.code !== 0) {
            return;
          }
          this.partnerList = res.data;
        });
    },
    getPermissions() {},
    // 获取数据
    getData() {
      this.$axios
        .get("/product/commodity/page", {
          params: {
            page: this.query.pageIndex,
            limit: this.query.pageSize,

            categoryId: this.query.categoryId,
            companyId: this.query.companyId,
            name: this.query.goodsName,
            enableStatus: this.query.enableStatus,
          },
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.tableData = res.data.list;
          this.pageTotal = res.data.total || 0;
          this.tableData.map((item, index) => {
            item.createDate = this.dateFormat(item.createDate);
            var pageIndex = this.query.pageIndex;
            var pageSize = this.query.pageSize;
            // console.log(pageIndex, pageSize);
            item.index = index + 1 + (pageIndex - 1) * this.query.pageSize;

            // item.radio = item.radio == 1 ? "否" : "是";
          });
          console.log("商品管理列表", this.tableData);
        });
    },
    // 是否热销
    selectHotSale(row) {
      console.log(row);
      if (row.radio == "0") {
        this.setHotSale(row);
      } else if (row.radio == "1") {
        this.deleteHotSale(row);
      }
    },
    setHotSale(row) {
      this.$axios
        .post("product/hotcakes", {
          commodityId: row.id,
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            row.radio = row.radio == "1" ? "0" : "1";
            return;
          }
          this.$message.success("添加热销成功");
          this.getData();
        })
        .catch(() => {});
    },
    deleteHotSale(row) {
      this.$axios
        .delete(`product/hotcakes/${row.id}`)
        .then(({ data: res }) => {
          if (res.code != 0) {
            row.radio = row.radio == "1" ? "0" : "1";
            return;
          }
          this.$message.success("取消热销");
          this.getData();
        })
        .catch(() => {});
    },

    // 导出
    handleExport() {
      NProgress.start();
      this.$axios
        .get("/product/commodity/export", {
          params: {
            categoryId: this.query.categoryId,
            companyId: this.query.companyId,
            name: this.query.goodsName,
            enableStatus: this.query.enableStatus,
          },
          responseType: "blob",
        })
        .then((res) => {
          const link = document.createElement("a");
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          // let num = "";
          // for (let i = 0; i < 10; i++) {
          //   num += Math.ceil(Math.random() * 10);
          // }
          link.setAttribute(
            "download",
            "商品 " + this.dateFormat(Date.now(), "yyyy-mm-dd") + ".xls"
          );
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          NProgress.done();
        })
        .catch(() => {});
    },

    // 新增操作
    handleIncrease() {
      // 跳转到一个页面去新增, 不要弹框新增
      this.$router.replace({ path: "/product-increase" });
    },
    // 触发查询按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids[0] = row.id;
      util.delete.call(
        this,
        "/product/commodity",
        index,
        this.ids,
        this.getData
      );
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除
    delAllSelection() {
      var ids = this.multipleSelection.map((item) => {
        return item.id;
      });
      ids = [...new Set(ids)];
      util.delete.call(this, "/product/commodity", "", ids, this.getData);
    },
    // 编辑操作
    handleEdit(index, row) {
      console.log(row.id);
      // 跳转到商品详情编辑
      this.$router.push({
        path: "/product-detail",
        query: { id: row.id },
      });
    },
    // 获取商品 id
    getProductId(index, row) {
      console.log(index, row);
      this.$router.replace({
        path: "/banner-increase",
        query: { stuffId: row.id },
      });
    },

    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
    handleSizeChange(val) {
      this.$set(this.query, "pageSize", val);
      this.getData();
    },

    // 限制时间的范围：8.64e7 ( 86400000ms = 1000*24*60*60 )
    disabledDate(time) {
      //设置选择今天以及今天之后的日
      return time.getTime() < Date.now() - 8.64e7;
      //设置选择今天以及今天以前的日期
      return time.getTime() > Date.now();
      //设置选择今天之后的日期（不能选择当天时间）
      return time.getTime() < Date.now();
      //设置选择今天之前的日期（不能选择当天）
      return time.getTime() > Date.now() - 8.64e7;
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
  /* display: flex;
  justify-content: flex-start; */
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.blue {
  color: rgba(0, 0, 255, 0.6);
}
.mr10 {
  margin-right: 10px;
  width: 120px;
  float: left;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.red {
  color: red;
}

/* .is-selected {
  color: #1989fa;
} */
/* .el-calendar {
  width: 550px;
  box-shadow: 1px 1px 3px #ccc;
} */
/* .el-select-dropdown__item.hover {
  width: 650px;
  height: 650px;
} */
</style>
